﻿using System;
using System.Collections.Concurrent;
using System.IO;
using System.Web.Hosting;
using HandlebarsDotNet;
using System.Collections.Generic;

namespace SX.Utils
{
    public class HandlebarsMvcView
    {
#if !DEBUG
        static ConcurrentDictionary<string, Func<object, string>> compiledViews = new ConcurrentDictionary<string, Func<object, string>>();
#endif
        private Func<object, string> render;

        public HandlebarsMvcView(string physicalpath, IHandlebars handlebars)
        {
            var templatePath = physicalpath;
            var version = HostingEnvironment.VirtualPathProvider.GetCacheKey(templatePath);
            var key = templatePath + "_" + version;
#if !DEBUG
           render = compiledViews.GetOrAdd(key, (k) =>
            {
                var compiledView = handlebars.CompileView(templatePath);
                return compiledView;
            });
#else
            render = handlebars.CompileView(templatePath);
#endif

        }

        public void Render(object data, TextWriter writer)
        {
            writer.Write(render(data));
        }

        public string Render(object data)
        {
            //List<object> paramodelList = new List<object>();
            //if (data != null)
            //{
            //    paramodelList.Add(data);
            //}
            //paramodelList.Add( new { title = "test" });
            //DynamicViewModel model =   new DynamicViewModel(paramodelList.ToArray());
           
            return render(data);
        }
    }
}
